<template>
  <PageWrapper dense>
    <CollapseContainer title="产品信息">
      <BasicForm @register="registerForm">
        <!-- 产品信息 -->
        <template #list>
          <div class="w-full px-6 flex gap-8px">
            <a-button @click="handleInsert(1)">添加产品</a-button>
            <a-button @click="handleInsert(2)">添加其他款项</a-button>
            <a-button danger @click="handleRemoveSelect">选中删除</a-button>
          </div>
          <VxeBasicTable ref="tableRef" v-bind="gridOptions" />
        </template>
      </BasicForm>
    </CollapseContainer>
  </PageWrapper>

  <ProductDrawer @register="registerDrawer" @select="selectGoods" />
</template>

<script setup lang="ts">
import { BasicForm, useForm } from '@/components/Form';
import { ref, reactive, computed, watch } from 'vue';
import { drawerSchemas3, vxeTableColumns, validRules } from '../orderRefund.data';
import { CollapseContainer } from '@/components/Container';
import { PageWrapper } from '@/components/Page';
import { BasicTableProps, VxeBasicTable } from '@/components/VxeTable';
import { cloneDeep } from 'lodash-es';
import type { VxeGridInstance } from 'vxe-table';
import ProductDrawer from '@/components/productDrawer/ProductDrawer.vue';
import { useDrawer } from '@/components/Drawer';
const [registerDrawer, { openDrawer }] = useDrawer();
defineOptions({ name: 'productEdit' });
const [registerForm, { setFieldsValue, validate }] = useForm({
  // layout: 'vertical',
  labelWidth: 100,
  name: 'user-drawer',
  showActionButtonGroup: false,
  baseColProps: { span: 12 },
  schemas: drawerSchemas3,
});
const tableRef = ref<VxeGridInstance>();
const gridOptions = reactive<BasicTableProps>({
  id: 'CodeGenVxeTable',
  keepSource: true,
  border: true,
  editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
  columns: vxeTableColumns,
  toolbarConfig: {
    enabled: false,
  },
  columnConfig: {
    resizable: true,
  },
  data: [],
  proxyConfig: {
    // 必须设置
    enabled: false,
  },
  editRules: validRules,
});

async function handleInsert(type: number) {
  if (type === 1) {
    return openDrawer();
  }
  const $table = tableRef.value;
  if ($table) {
    const record = {
      name: '运费',
      productId: '',
      price: '',
      num: '',
      amount: '',
      type: 1,
      remark: '',
    };
    // 在尾部插入
    await $table.insertAt(record, -1);
  }
}

function handleRemoveSelect() {
  const $table = tableRef.value;
  if ($table) {
    $table.removeCheckboxRow();
  }
}
async function handleTableValidate() {
  const $table = tableRef.value;
  if (!$table) {
    return;
  }
  const hasError = await $table.validate();
  if (hasError) {
    return Promise.reject(new Error('编辑表格校验失败'));
  }
  // 使用getTableData才能拿到修改后的数据
  const tableData = $table.getTableData();
  return Promise.resolve(cloneDeep(tableData.fullData));
}
const goodsData = computed(() => {
  const $table = tableRef.value as any;
  return $table ? $table.getTableData() : []
})
watch(
  () => goodsData,
  (val) => {
    const tableData: any = val.value.tableData;
    let spuMoney = 0;
    let otherMoney = 0;
    let totalAmount = 0;
    tableData.forEach((item: any) => {
      if (item.type === 0) {
        spuMoney += Number(item.num * item.price)
      }
      if (item.type === 1) {
        otherMoney += Number(item.num * item.price)
      }
      totalAmount += Number(item.num * item.price)
    });
    setFieldsValue({ spuMoney, otherMoney, totalAmount })
  },
  {
    deep: true
  })
const selectGoods = (goods: any) => {
  const $table = tableRef.value;
  if ($table) {
    goods.forEach(async (good: any) => {
      const record = {
        name: good.spuName,
        productId: good.spuId,
        price: '',
        num: '',
        amount: '',
        type: 0,
        remark: good.spuDesc,
      };
      // 在尾部插入
      await $table.insertAt(record, -1);
    });

  }
}
async function handleSubmit() {
  try {
    const data = {
      ...(await validate()),
      list: await handleTableValidate(),
    };
    return data;
  } catch (e) {
    console.log('e', e);
  } finally {
  }
}
const setFormData = (data: any) => {
  setFieldsValue(data);
  gridOptions.data = data.list;
};
defineExpose({ handleSubmit, setFormData });
</script>
